﻿namespace StockSharp.AlfaDirect
{
	using System.Collections.Generic;

	using Ecng.Collections;
	using Ecng.Common;
	using StockSharp.BusinessEntities;
	using System;

	static class AlfaUtils
	{
		/// <summary>
		/// Converts a board code to the security type
		/// </summary>
		/// <param name="boardCode">Код торгового раздела: FUTURES, MOPTIONS, MCX_SHR_LSTB, MCX_SHR_NLST...</param>
		/// <returns>Security type</returns>
		public static SecurityTypes BoardCodeToSecurityType(string boardCode)
		{
			SecurityTypes result;

			switch (boardCode)
			{
				case "FUTURES":
					result = SecurityTypes.Future;
					break;
				case "MOPTIONS":
					result = SecurityTypes.Option;
					break;
				default:
					result = SecurityTypes.Stock;
					break;
			}

			return result;
		}

		public static SecurityStates SecurityStateFromAlfa(string status)
		{
			return (status.To<int>() == 6) ? SecurityStates.Trading : SecurityStates.Stoped;
		}

		public static ExchangeBoard ExchangeBoardCodeToExchangeBoard(string exCode)
		{
			ExchangeBoard exchangeBoard;

			switch (exCode)
			{
				case "FORTS":
				case "RTS":
					exchangeBoard = ExchangeBoard.Forts;
					break;
				case "MICEX":
					exchangeBoard = ExchangeBoard.Micex;
					break;
				default:
					exchangeBoard = new ExchangeBoard { Code = exCode };
					break;
			}

			return exchangeBoard;
		}

		public static OrderDirections OrderDirectionsFromAlfa (string buySell)
		{
			return buySell == "B" ? OrderDirections.Buy : OrderDirections.Sell;
		}

		public static OrderDirections OrderDirectionsFromAlfa(int buySell)
		{
			return buySell == 1 ? OrderDirections.Sell : OrderDirections.Buy;
		}

		public static string OrderDirectionsToAlfa(OrderDirections direction)
		{
			return direction == OrderDirections.Buy ? "B" : "S";
		}

		public static DateTime ExpirityDateToAlfa(DateTime? endTime, DateTime marketTime)
		{
			return endTime == null ? marketTime.Date.AddTicks(new TimeSpan(23, 55, 00).Ticks) : endTime.Value;
		}

		public static Dictionary<int, List<string[]>> Filter(string data, SynchronizedOrderedList<int> subscribers)
		{
			var result = new Dictionary<int, List<string[]>>();

			if(data == null)
			{
				return result;
			}

			var strs = data.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

			foreach (var str in strs)
			{
				var details = str.Split('|');

				if(details[0].IsEmpty())
					continue;

				var paperNo = details[0].To<int>();

				if (subscribers.IsEmpty() || subscribers.Contains(paperNo))
				{
					if (!result.ContainsKey(paperNo))
					{
						result[paperNo] = new List<string[]>();
					}

					result[paperNo].Add(details);
				}
			}

			return result;
		}
	}
}